import { nanoid } from 'nanoid';
import { createValidationError } from '../utils/error-handler.js';
import { TemplateManager } from './template.js';

export interface GenerateExcelArgs {
  name: string;
  fields: string[];
  data: Array<string[]>;
}

// In-memory session management for Excel files
const excelSessions = new Map<string, string>();

class ExcelGenerator {
  private templateManager = new TemplateManager();

  async createExcelSession(name: string, fields: string[]): Promise<string> {
    const sessionId = nanoid();
    const resultPath = await this.templateManager.copyTemplate(
      process.env.DEFAULT_TEMPLATE as string,
      name
    );

    const { headerRow, fieldPositions } = await this.templateManager.findFieldPositions(
      resultPath,
      fields
    );

    excelSessions.set(
      sessionId,
      JSON.stringify({ resultPath, fieldPositions, headerRow, nextRow: headerRow + 1 })
    );

    return sessionId;
  }

  async appendToExcelSession(sessionId: string, data: Array<string[]>): Promise<void> {
    const sessionData = excelSessions.get(sessionId);
    if (!sessionData) {
      throw createValidationError('Invalid session ID');
    }

    const { resultPath, fieldPositions, headerRow, nextRow } = JSON.parse(sessionData);
    await this.templateManager.writeToTemplate(
      resultPath,
      data,
      fieldPositions,
      headerRow,
      nextRow
    );
    excelSessions.set(
      sessionId,
      JSON.stringify({
        resultPath,
        fieldPositions,
        headerRow,
        nextRow: nextRow + data.length,
      })
    );
  }

  async finalizeExcelSession(sessionId: string): Promise<string> {
    const sessionData = excelSessions.get(sessionId);
    if (!sessionData) {
      throw createValidationError('Invalid session ID');
    }

    const { resultPath } = JSON.parse(sessionData);
    excelSessions.delete(sessionId);
    return resultPath;
  }
}

export const excelGenerator = new ExcelGenerator();
